﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.PermissionManagement.IPermissionManagement;
using SportsPlatform.Base;
using SqlSugar;
using Abp.ObjectMapping;
using SportsPlatform.Consts;
using SportsPlatform.Query.PermissionManagement.RoleFunction;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Query.PermissionManagement.BaseQuery;
using SportsPlatform.Dto.PermissionManagement.RoleFunction;
using Abp.Application.Services;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;
using SportsPlatform.SqlExecuter;

namespace SportsPlatform.PermissionManagement.PermissionManagement
{
    /// <summary>
    /// 角色功能对应表
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class RoleFunctionService : SportsPlatformAppServiceBase, IRoleFunctionService
    {
        private readonly IRepository<FunctionInfo, Guid> _functionInfoRepository;

        private readonly IRepository<UserInfo, Guid> _userinfoRepository;

        private readonly IRepository<RoleFunction, Guid> _roleFunctionRepository;

        private readonly IRepository<RoleInfo, Guid> _roleinfoRepository;

        private readonly ISqlExecuterRepository _sqlExecuterRepository;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="functionInfoRepository"></param>
        /// <param name="userinfoRepository"></param>
        /// <param name="roleFunctionRepository"></param>
        public RoleFunctionService(IRepository<FunctionInfo, Guid> functionInfoRepository, IRepository<UserInfo, Guid> userinfoRepository,
            IRepository<RoleFunction, Guid> roleFunctionRepository, ISqlExecuterRepository sqlExecuterRepository, IRepository<RoleInfo, Guid> roleinfoRepository
            , IHttpContextAccessor context) : base(context)
        {
            _functionInfoRepository = functionInfoRepository;
            _userinfoRepository = userinfoRepository;
            _roleFunctionRepository = roleFunctionRepository;
            _roleinfoRepository = roleinfoRepository;
            _sqlExecuterRepository = sqlExecuterRepository;
        }

        /// <summary>
        /// 新增信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddOrUpdateRoleFunction(AddOrUpdateRoleFunctionQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                //新增编辑前删除所有
                //var sql = "UPDATE PM_RoleFunction SET IsDeleted=1,DeleteTime='" + DateTime.Now + "',DeleteUserId='" + token.Id + "' where RoleId='" + query.RoleId + "'";
                //_sqlExecuterRepository.Execute(sql, null);

                //判断角色Id是否存在
                if (_roleinfoRepository.FirstOrDefault(info => info.Id == query.RoleId) != null)
                {
                    //判断功能Id集合
                    if (query.List != null && query.List.Count > 0)
                    {
                        //循环遍历传入的功能Id集合
                        query.List.ForEach(async item =>
                        {
                            //判断角色Id+功能Id是否存在，存在更新，不存在则新增
                            var rolefunction = _roleFunctionRepository.FirstOrDefault(info => info.RoleId == query.RoleId && info.FunctionId == item.FunctionId);
                            if (rolefunction != null)
                            {
                                rolefunction.States = item.States;
                                rolefunction.IsDeleted = item.States == true ? false : true;
                                rolefunction.UpdateTime = DateTime.Now;
                                rolefunction.UpdateUserId = token.Id;
                                await _roleFunctionRepository.UpdateAsync(rolefunction);
                            }
                            else
                            {
                                RoleFunction addrolefunction = new RoleFunction();
                                addrolefunction.RoleId = query.RoleId;
                                addrolefunction.FunctionId = item.FunctionId;
                                addrolefunction.States = true;
                                addrolefunction.IsDeleted = false;
                                addrolefunction.CreateTime = DateTime.Now;
                                addrolefunction.CreateUserId = token.Id;
                                await _roleFunctionRepository.InsertAsync(addrolefunction);
                            }
                        });
                        baseResultDto.IsSuccess = true;
                        baseResultDto.Code = HttpResultCode.Success;
                        baseResultDto.Message = "新增成功！";
                    }
                    else
                    {
                        baseResultDto.IsSuccess = false;
                        baseResultDto.Code = HttpResultCode.Fail;
                        baseResultDto.Message = "传入List不能为空！";
                    }
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "传入角色Id不存在！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }


        /// <summary>
        /// 获取角色对应的功能菜单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetRoleFunctionDto>> GetRoleFunctionList(GetRoleFunctionQuery query)
        {
            PagePagingDto<GetRoleFunctionDto> pagePagingDto = new PagePagingDto<GetRoleFunctionDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                //获取tokenId的个人信息
                var userinfo = _userinfoRepository.FirstOrDefault(info => info.Id == token.Id);

                if (userinfo != null)
                {
                    //判断是否超级管理，是就获取所有
                    if (userinfo.IsAllPermission == true)
                    {
                        //超级管理员
                        var functioninfolist = (await _functionInfoRepository.GetAllListAsync(info => info.IsDeleted == false && info.States == true && info.FunctionIsAvailable == true))
                            .WhereIF(!string.IsNullOrEmpty(query.FunctionName), info => info.FunctionName.Contains(query.FunctionName))
                            .WhereIF(!string.IsNullOrEmpty(query.FunctionNumber), info => info.FunctionNumber.Contains(query.FunctionNumber))
                            .OrderByDescending(info => info.CreateTime)
                            .ToList();
                        var functioninfopage = functioninfolist
                          .Skip((query.PageIndex - 1) * query.PageSize)
                          .Take(query.PageSize)
                         .ToList();
                        if (functioninfopage != null && functioninfopage.Count > 0)
                        {
                            pagePagingDto.IsSuccess = true;
                            pagePagingDto.Code = HttpResultCode.Success;
                            pagePagingDto.Message = "查询成功！";
                            pagePagingDto.TotalCount = functioninfolist.Count;
                            var functioninfopagedto = ObjectMapper.Map<List<GetRoleFunctionDto>>(functioninfopage);
                            var funclist = await _functionInfoRepository.GetAllListAsync();
                            functioninfopagedto.ForEach(item =>
                            {
                                item.ParentName = item.ParentId != Guid.Empty ? funclist.Where(info => info.Id == item.ParentId).FirstOrDefault().FunctionName : "";
                                item.ParentNumber = item.ParentId != Guid.Empty ? funclist.Where(info => info.Id == item.ParentId).FirstOrDefault().FunctionNumber : "";
                                item.IsPermission = false;

                            });
                            //判断是不是在进行权限设置，是就需要返回是否有权限
                            if (query.PermissionSettingsRoleId != null || query.PermissionSettingsRoleId == Guid.Empty)
                            {
                                var settingfunctionlist = _roleFunctionRepository.GetAllList(info => info.RoleId == query.PermissionSettingsRoleId && info.IsDeleted == false && info.States == true);
                                if (settingfunctionlist != null && settingfunctionlist.Count > 0)
                                {
                                    settingfunctionlist.ForEach(func =>
                                    {
                                        functioninfopagedto.ForEach(item =>
                                        {
                                            if (func.FunctionId == item.Id)
                                            {
                                                item.IsPermission = true;
                                            }
                                        });
                                    });
                                }
                            }
                            pagePagingDto.Data = functioninfopagedto;
                        }
                        else
                        {
                            pagePagingDto.IsSuccess = false;
                            pagePagingDto.Code = HttpResultCode.SqlError;
                            pagePagingDto.Message = "未查询到相关功能信息！";
                        }
                    }
                    else if (userinfo.RoleId != null && userinfo.RoleId != Guid.Empty)
                    {
                        //获取角色对应功能
                        var rolefunctionlist = (await _roleFunctionRepository.GetAllListAsync(info => info.States == true && info.IsDeleted == false && info.RoleId == userinfo.RoleId))
                             .WhereIF(!string.IsNullOrEmpty(query.FunctionName), info => _functionInfoRepository.FirstOrDefault(func => func.Id == info.FunctionId).FunctionName.Contains(query.FunctionName))
                             .WhereIF(!string.IsNullOrEmpty(query.FunctionNumber), info => _functionInfoRepository.FirstOrDefault(func => func.Id == info.FunctionId).FunctionNumber.Contains(query.FunctionNumber))
                             .OrderByDescending(info => info.CreateTime)
                             .ToList();
                        var rolefunctionpage = rolefunctionlist
                          .Skip((query.PageIndex - 1) * query.PageSize)
                          .Take(query.PageSize)
                         .ToList();
                        if (rolefunctionpage != null && rolefunctionpage.Count > 0)
                        {
                            pagePagingDto.IsSuccess = true;
                            pagePagingDto.Code = HttpResultCode.Success;
                            pagePagingDto.Message = "查询成功！";
                            pagePagingDto.TotalCount = rolefunctionlist.Count;
                            List<GetRoleFunctionDto> getRoleFunctionDtos = new List<GetRoleFunctionDto>();
                            var funclist = await _functionInfoRepository.GetAllListAsync();
                            rolefunctionpage.ForEach(item =>
                            {
                                var functioninfo = funclist.Where(info => info.Id == item.FunctionId).FirstOrDefault();
                                GetRoleFunctionDto getRoleFunctionDto = ObjectMapper.Map<GetRoleFunctionDto>(functioninfo);
                                getRoleFunctionDto.ParentName = getRoleFunctionDto.ParentId != Guid.Empty ? funclist.Where(info => info.Id == getRoleFunctionDto.ParentId).FirstOrDefault().FunctionName : "";
                                getRoleFunctionDto.ParentNumber = getRoleFunctionDto.ParentId != Guid.Empty ? funclist.Where(info => info.Id == getRoleFunctionDto.ParentId).FirstOrDefault().FunctionNumber : "";
                                getRoleFunctionDto.IsPermission = false;
                                getRoleFunctionDtos.Add(getRoleFunctionDto);
                            });

                            //判断是不是在进行权限设置，是就需要返回是否有权限
                            if (query.PermissionSettingsRoleId != null || query.PermissionSettingsRoleId == Guid.Empty)
                            {
                                var settingfunctionlist = _roleFunctionRepository.GetAllList(info => info.RoleId == query.PermissionSettingsRoleId && info.IsDeleted == false && info.States == true);
                                if (settingfunctionlist != null && settingfunctionlist.Count > 0)
                                {
                                    settingfunctionlist.ForEach(func =>
                                    {
                                        getRoleFunctionDtos.ForEach(item =>
                                        {
                                            if (func.FunctionId == item.Id)
                                            {
                                                item.IsPermission = true;
                                            }
                                        });
                                    });
                                }
                            }
                            pagePagingDto.Data = getRoleFunctionDtos;
                        }
                        else
                        {
                            pagePagingDto.IsSuccess = false;
                            pagePagingDto.Code = HttpResultCode.SqlError;
                            pagePagingDto.Message = "未查询到相关功能信息！";
                        }

                    }
                    else
                    {
                        //不是超级管理员，也没有角色Id，就没有权限
                        pagePagingDto.IsSuccess = false;
                        pagePagingDto.Code = HttpResultCode.Fail;
                        pagePagingDto.Message = "没有权限！";
                    }
                }
            }
            catch (Exception e)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = e.Message.ToString();
            }
            return pagePagingDto;
        }

        /// <summary>
        /// 获取功能菜单编号
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<GetFunctionNumberDto>> GetFunctionNumberList()
        {
            ResultListDto<GetFunctionNumberDto> resultListDto = new ResultListDto<GetFunctionNumberDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                //获取tokenId的个人信息
                var userinfo = _userinfoRepository.FirstOrDefault(info => info.Id == token.Id);
                if (userinfo != null)
                {
                    //判断是否超级管理，是就获取所有
                    if (userinfo.IsAllPermission == true)
                    {
                        //超级管理员
                        var functioninfolist = await _functionInfoRepository.GetAllListAsync(info => info.IsDeleted == false && info.States == true && info.FunctionIsAvailable == true);
                        if (functioninfolist != null && functioninfolist.Count > 0)
                        {
                            resultListDto.IsSuccess = true;
                            resultListDto.Code = HttpResultCode.Success;
                            resultListDto.Message = "查询成功！";
                            List<GetFunctionNumberDto> getFunctionNumberDtos = new List<GetFunctionNumberDto>();
                            functioninfolist.ForEach(item =>
                            {

                                //去重
                                bool IsExistence = false;//判断是否存在
                                getFunctionNumberDtos.ForEach(nuber =>
                                {
                                    if (string.IsNullOrEmpty(item.FunctionNumber) || item.FunctionNumber.Equals(nuber.FunctionNumber))
                                    {
                                        IsExistence = true;
                                    }
                                });
                                if (!IsExistence)
                                {
                                    getFunctionNumberDtos.Add(new GetFunctionNumberDto() { FunctionNumber = item.FunctionNumber });
                                }

                            });
                            resultListDto.Count = getFunctionNumberDtos.Count;
                            resultListDto.Data = getFunctionNumberDtos;
                        }
                        else
                        {
                            resultListDto.IsSuccess = false;
                            resultListDto.Code = HttpResultCode.SqlError;
                            resultListDto.Message = "未查询到相关功能信息！";
                        }
                    }
                    else if (userinfo.RoleId != null)
                    {
                        //获取角色对应功能
                        var rolefunctionlist = await _roleFunctionRepository.GetAllListAsync(info => info.States == true && info.IsDeleted == false && info.RoleId == userinfo.RoleId);
                        if (rolefunctionlist != null && rolefunctionlist.Count > 0)
                        {
                            resultListDto.IsSuccess = true;
                            resultListDto.Code = HttpResultCode.Success;
                            resultListDto.Message = "查询成功！";

                            List<GetFunctionNumberDto> getFunctionNumberDtos = new List<GetFunctionNumberDto>();
                            rolefunctionlist.ForEach(item =>
                            {

                                var functioninfo = _functionInfoRepository.FirstOrDefault(info => info.Id == item.FunctionId);
                                //去重
                                bool IsExistence = false;//判断是否存在
                                getFunctionNumberDtos.ForEach(nuber =>
                                {
                                    if (string.IsNullOrEmpty(functioninfo.FunctionNumber) || functioninfo.FunctionNumber.Equals(nuber.FunctionNumber))
                                    {
                                        IsExistence = true;
                                    }
                                });
                                if (!IsExistence)
                                {
                                    getFunctionNumberDtos.Add(new GetFunctionNumberDto() { FunctionNumber = functioninfo.FunctionNumber });
                                }
                            });
                            resultListDto.Count = getFunctionNumberDtos.Count;
                            resultListDto.Data = getFunctionNumberDtos;
                        }
                        else
                        {
                            resultListDto.IsSuccess = false;
                            resultListDto.Code = HttpResultCode.SqlError;
                            resultListDto.Message = "未查询到相关功能信息！";
                        }

                    }
                    else
                    {
                        //不是超级管理员，也没有角色Id，就没有权限
                        resultListDto.IsSuccess = false;
                        resultListDto.Code = HttpResultCode.Fail;
                        resultListDto.Message = "没有权限！";
                    }
                }
            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }
        /// <summary>
        ///  获取树型功能菜单，只能获取自己已有的权限树型菜单
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<GetRoleFunctionTreeListDto>> GetRoleFunctionTreeList(GetRoleFunctionTreeListQuery query)
        {
            ResultListDto<GetRoleFunctionTreeListDto> resultListDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var rolefunclist = await _roleFunctionRepository.GetAllListAsync(info => info.States == true && info.IsDeleted == false);
                //判断是否超级管理，是就获取所有
                if (token.IsAllPermission == true)
                {
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = GetFunctionInfoTreeList(Guid.Empty, Guid.Empty, (query.RoleId!=null && query.RoleId!=Guid.Empty)? rolefunclist.Where(info=>info.RoleId==query.RoleId).ToList(): null);
                }
                else if (token.RoleId != null && token.RoleId != Guid.Empty)
                {
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = GetFunctionInfoTreeList(Guid.Empty, (Guid)token.RoleId, (query.RoleId != null && query.RoleId != Guid.Empty) ? rolefunclist.Where(info => info.RoleId == query.RoleId).ToList() : null);
                }
                else
                {
                    //不是超级管理员，也没有角色Id，就没有权限
                    resultListDto.IsSuccess = false;
                    resultListDto.Code = HttpResultCode.Fail;
                    resultListDto.Message = "没有权限！";
                }
            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 递归获取树型菜单
        /// </summary>
        /// <param name="ParentId"></param>
        /// <param name="RoleId"></param>
        /// <param name="Permissions"></param>
        /// <returns></returns>
        public List<GetRoleFunctionTreeListDto> GetFunctionInfoTreeList(Guid ParentId, Guid RoleId, List<RoleFunction> Permissions)
        {
            List<GetRoleFunctionTreeListDto> resultListDto = new();
            try
            {
                var functioninfolist = _functionInfoRepository.GetAllList(info => info.ParentId == ParentId && info.States == true && info.IsDeleted == false);
                if (functioninfolist != null && functioninfolist.Count > 0)
                {
                    foreach (var item in functioninfolist)
                    {
                        var treelist = GetFunctionInfoTreeList(item.Id, RoleId, Permissions);
                        GetRoleFunctionTreeListDto children = new();
                        children.Id = item.Id;
                        children.FunctionName = item.FunctionName;
                        children.IsPermission = Permissions == null ? false : (Permissions.FirstOrDefault(info => info.FunctionId == item.Id) != null ? true : false);
                        children.Children = (treelist != null && treelist.Count > 0) ? treelist : null;
                        if (RoleId == Guid.Empty)
                        {
                            resultListDto.Add(children);
                        }
                        else if (_roleFunctionRepository.FirstOrDefault(info => info.RoleId == RoleId && info.FunctionId == item.Id && info.IsDeleted == false && info.States == true) != null)
                        {
                            resultListDto.Add(children);
                        }
                    }
                }
            }
            catch
            {

            }
            return resultListDto;
        }
    }
}
